<?php
/**
 * @Author: liuhongbin
 * @Email: 514660094@qq.com
 * @Date: 2019-02-12 16:15:10
 * @Description:
 * @LastEditors: liuhongbin
 * @LastEditTime: xxx
 */

namespace app\controller\adminapi\platform\work_wechat;

use app\controller\adminapi\platform\PlatformController;
use app\common\model\system\Config;
use hiduoke\services\workWechat\WorkWechatOpen;
use think\App;
use app\common\model\platform\Platform;
use hiduoke\services\FormBuilder as Form;

/**
 * Class WorkWechat 企业微信
 * @package app\controller\adminapi\platform\work_wechat
 * User: liuhongbin
 * Date: 2022-07-17 17:25
 */
class WorkWechat extends PlatformController
{
    /**
     * @var Platform
     */
    public $model;
    /**
     * @var \EasyWeChat\OpenWork\Application|mixed
     */
    private $openApp;

    public function __construct(App $app, Platform $model)
    {
        parent::__construct($app);
        $this->model = $model;
        $this->openApp = (new workWechatOpen())->getOpenApp();
    }

    /**
     * 显示企业微信列表
     * @Route("wechat", method="GET")
     * @return \think\Response
     */
    public function index()
    {
        //
        return $this->success("ok");
    }

    /**
     * 显示创建企业微信表单页.
     * @Route("wechat/create", method="GET")
     * @return \think\Response
     */
    public function create()
    {
        return $this->getForm(0);
    }

    /**
     * 保存新建的企业微信
     * @Route("wechat", method="POST")
     * @param \think\Request $request
     * @return \think\Response
     */
    public function save()
    {
        return $this->saveForm(0);
    }

    /**
     * 显示编辑企业微信表单页.
     * @Route("wechat/id/edit", method="GET")
     * @param int $id
     * @return \think\Response
     */
    public function edit($id)
    {
        return $this->getForm($id);
    }

    public function getForm($id)
    {
        $rule = array();
        //创建表单
        $row = $this->model->where(['plaid' => $id])->findOrEmpty();
        if ($row->isEmpty()) {
            //新增
            $form = Form::createForm("/adminapi/platform/work_wechat/index")->setMethod("POST");
            $title = "新增企业微信平台";
        } else {
            $form = Form::createForm("/adminapi/platform/work_wechat/index/" . $id)->setMethod("PUT");
            $title = "编辑企业微信平台";
        }
        //新增表单
        $rule[] = Form::hidden('type', 3);
        if ($id) {
            //没有永久授权码
            $auth_type = (new Config())->getValueByKey("workWechat")['auth_type'] ?? 'manual';
            if ($auth_type == 'auto') {
                //自由选择授权
                $rule[] = Form::radio('auth_type', '授权方式', $row['auth_type'] ?? 0)
                    ->options([
                        ['label' => '手动配置', 'value' => 0],
                        ['label' => '服务商授权', 'value' => 1],
                    ])
                    ->effect(['help' => '设置应用授权方式，手动配置的话需要单独设置企业微信的授权信息，扫码授权的话只需要用企业微信扫码即可'])
                    ->appendControl(1, [
                        Form::dkWorkWechatOpen('config_permanent_code', "扫码授权", $row['config']['permanent_code'] ?? '')
                            ->effect(['help' => '点击按钮使用企业微信扫码授权，授权后请等待页面自动跳转完成账号授权'])
                    ])
                    ->appendControl(1, [
                        Form::hidden('config_permanent_code', $row['config']['permanent_code'] ?? '')
                    ]);
            } elseif ($auth_type == 'open') {
                //扫码授权
                $rule[] = Form::dkWorkWechatOpen('config_permanent_code', "扫码授权", $row['config']['permanent_code'] ?? '')
                    ->effect(['help' => '点击按钮使用企业微信扫码授权，授权后请等待页面自动跳转完成账号授权']);
            }

        } else {
            $rule[] = Form::ElAlert()->type('warning')->showIcon(true)->title('提示')
                ->prop('style', 'margin-bottom: 20px;')
                ->description('请先保存平台信息，再进行授权设置，创建成功后进入当前企业微信平台->系统设置->进行详细配置');
        }
        $rule[] = Form::number('sort', '排序', $row->sort ?? '');
        $rule[] = Form::input('name', '企业名称', $row->name ?? '')->required();
        if ($row['auth_type'] == 0 || $auth_type == 'manual') {
            $rule[] = Form::dkInput('corp_id', '企业ID', $row['corp_id'] ?? '', '填写企业ID，在：【我的企业】-【企业信息】-【企业ID】(最下面)，PS:扫码授权的会自动获取')->required();
        } else {
            $rule[] = Form::dkInput('corp_id', '授权企业ID', $row['corp_id'] ?? '', '当前为授权的企业ID,无需修改，值可能与后台不同')->required()->disabled(true);
        }
//        $rule[] = Form::dkInput('config_corp_id', '企业ID', $row['config']['corp_id'] ?? '', '填写企业ID，在：【我的企业】-【企业信息】-【企业ID】(最下面)')->required();
        $rule[] = Form::input('description', '描述', $row->description ?? '');
        $rule[] = Form::dkImage('logo', '图标', $row->logo ?? '')->appendToBody();


        $form->setTitle($title)->setRule($rule);
        return $this->success("", Form::getFormData($form));
    }

    public function saveForm($id)
    {
        $wallet = $this->userInfo['wallet'];
        if ($wallet['work_wechat'] <= $wallet['use_count']['work_wechat']) {
            return $this->error("创建次数不足");
        }
        $formData = getFormData();
        if (!$id) {
            $formData['uid'] = $this->userInfo['uid'];
        }
        $row = $this->model->findOrEmpty($id);
        $row->save($formData);
        return $this->success("提交成功", ['plaid' => $row->plaid]);
    }

    /**
     * 保存更新的企业微信
     * @Route("wechat/id", method="PUT")
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update($id)
    {
        return $this->saveForm($id);
    }

    /**
     * 删除指定企业微信
     * @Route("wechat/id", method="DELETE")
     * @param int $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }

    /**
     * 获取企业微信服务商授权链接
     * @Route("wechat/auth", method="POST")
     * @param \think\Request $request
     * @return \think\Response
     */
    public function getOpenOauthUrl($id)
    {
        try {
            $code = $this->openApp->corp->getPreAuthCode()['pre_auth_code'];
            // 设置授权配置. 该接口可对某次授权进行配置
            $this->openApp->corp->setSession($code, [
                'app_id'    => [$this->openApp->config['suite_id']],
                'auth_type' => (new Config())->getValueByKey("workWechat")['qr_auth_type'] ?? '1',
            ]);
            //获取企业微信授权地址
            $callBack = url('/wh5/open/callback', ['plaid' => $id], true, true)->build();
            $url = $this->openApp->corp->getPreAuthorizationUrl($code, $callBack, '');
            return $this->success('ok', ['url' => $url]);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 被服务商授权后查询企业信息
     * @param $id
     * @return \think\response\Json
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getAuthorization($id)
    {
        try {
            $row = $this->model->where(['plaid' => $id])->findOrEmpty();
            $permanent_code = $row['config']['permanent_code'] ?? '';
            $corp_id = $row['corp_id'] ?? '';
            if ($permanent_code && $corp_id) {
                // TODO 这里写了个缓存，后期可能会有问题
                $res = $this->openApp->corp->getAuthorization($corp_id, $permanent_code);
                if (isset($res['errcode'])) {
                    return $this->error($res['errmsg']);
                }
                return $this->success('ok', $res);
            } else {
                return $this->error('不存在永久授权码');
            }
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }
}
